﻿using System;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using RHD.Common.Web.Components.Grid;
using RHD.Web.Infrastructure;

namespace RHD.Common.Web.Components {
	public static class GridExtension {

		public static MvcHtmlString Grid(this HtmlHelper html, string id, Action<GridColumns> columnsHandle, Action<GridBuilder> optionsHandle = null) {
			TagBuilder table = new TagBuilder("table");
			table.AddCssClass("table table-hover table-striped table-bordered");
			table.GenerateId(id);

			GridColumns columns = new GridColumns();
			if (columns != null)
				columnsHandle(columns);

			GridBuilder options = new GridBuilder();
			if (optionsHandle != null)
				optionsHandle(options);

			RenderScript(html, id, columns, options);
			return MvcHtmlString.Create(table.ToString());
		}

		private static void RenderScript(HtmlHelper html, string id, GridColumns columns, GridBuilder options) {
			StringBuilder json = new StringBuilder();
			json.AppendFormat("data: {{ url: \"{0}\", init: true, method: \"GET\" }},", options.url);
			json.AppendFormat("multiSelect: {0},", options.multiSelect.ToString().ToLower());

			StringBuilder cols = new StringBuilder();
			foreach (GridColumnBuilder builder in columns.columns) {
				cols.Append(cols.Length > 0 ? ", {" : "{");
				cols.AppendFormat("name: \"{0}\",", builder.name);
				cols.AppendFormat("title: \"{0}\",", builder.title);
				cols.AppendFormat("dataField: \"{0}\",", builder.dataField);
				cols.AppendFormat("dataType: \"{0}\",", builder.dataType.ToString().ToLower());
				cols.AppendFormat("active: {0},", builder.active.ToString().ToLower());

				StringBuilder sort = new StringBuilder();
				sort.AppendFormat("sortable: {0},", builder.active.ToString().ToLower());
				sort.AppendFormat("dataField: \"{0}\",", builder.dataField);
				sort.AppendFormat("dataType: \"{0}\"", builder.dataType.ToString().ToLower());
				cols.AppendFormat("sort: {{{0}}}", sort);

				cols.Append("}");
			}
			json.AppendFormat("columns: [{0}],", cols);

			json.AppendFormat("paging: {{");
			json.AppendFormat("	size: {0},", options.pageSize);
			json.AppendFormat("	options: [{0}]", string.Join(",", options.sizeOptions));
			json.AppendFormat("}}");

			html.AddScript(string.Format("$('#{0}').jGrid({{{1}}});", id, json));
		}
	}
}
